﻿
using CCSFeederCameraUI2.Data;
using CCSFeederCameraUI2.Data.Extensions;
using CCSFeederCameraUI2.Data.MClass;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NLog;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using RestSharp;
using SQLitePCL;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TonyMES.ViewModels
{
    public class ViewAViewModel : BindableBase
    {
        #region 变量
        private static Logger logger = LogManager.GetCurrentClassLogger();
        private readonly IEventAggregator aggregator;
        string partNum = string.Empty;
        int productIndex = 0;
        private readonly IDialogService _dialogService;
        private RestClient snclient,fpcclient, machineDataclient;
        #endregion
        #region 属性
        private string messageStr = string.Empty;
        public string MessageStr
        {
            get { return messageStr; }
            set { SetProperty(ref messageStr, value); }
        }
        private string machineCode;
        public string MachineCode
        {
            get { return machineCode; }
            set { SetProperty(ref machineCode, value); }
        }
        private string processCode;
        public string ProcessCode
        {
            get { return processCode; }
            set { SetProperty(ref processCode, value); }
        }
        private ObservableCollection<SelectRuleDisp> selectRuleList;
        public ObservableCollection<SelectRuleDisp> SelectRuleList
        {
            get { return selectRuleList; }
            set { SetProperty(ref selectRuleList, value); }
        }
        private ObservableCollection<Tony_LOT_NODisp> tony_LOT_NOs;
        public ObservableCollection<Tony_LOT_NODisp> Tony_LOT_NOs
        {
            get { return tony_LOT_NOs; }
            set { SetProperty(ref tony_LOT_NOs, value); }
        }
        private string lotNo;
        public string LotNo
        {
            get { return lotNo; }
            set { SetProperty(ref lotNo, value); }
        }
        private string productNo;
        public string ProductNo
        {
            get { return productNo; }
            set { SetProperty(ref productNo, value); }
        }
        private string uPLotNo;
        public string UPLotNo
        {
            get { return uPLotNo; }
            set { SetProperty(ref uPLotNo, value); }
        }
        #endregion
        #region 命令
        private DelegateCommand<object> textBoxLostFocusCommand;
        public DelegateCommand<object> TextBoxLostFocusCommand =>
            textBoxLostFocusCommand ?? (textBoxLostFocusCommand = new DelegateCommand<object>(ExecuteTextBoxLostFocusCommand));
        private DelegateCommand appLoadedEventCommand;
        public DelegateCommand AppLoadedEventCommand =>
            appLoadedEventCommand ?? (appLoadedEventCommand = new DelegateCommand(ExecuteAppLoadedEventCommand));
        private DelegateCommand<object> selectRuleCheckBoxCommand;
        public DelegateCommand<object> SelectRuleCheckBoxCommand =>
            selectRuleCheckBoxCommand ?? (selectRuleCheckBoxCommand = new DelegateCommand<object>(ExecuteSelectRuleCheckBoxCommand));
        private DelegateCommand<object> selectProductLotSettingCommand;
        public DelegateCommand<object> SelectProductLotSettingCommand =>
            selectProductLotSettingCommand ?? (selectProductLotSettingCommand = new DelegateCommand<object>(ExecuteSelectProductLotSettingCommand));
        private DelegateCommand addCommand;
        public DelegateCommand AddCommand =>
            addCommand ?? (addCommand = new DelegateCommand(ExecuteAddCommand));
        private DelegateCommand<object> deletCommand;
        public DelegateCommand<object> DeletCommand =>
            deletCommand ?? (deletCommand = new DelegateCommand<object>(ExecuteDeletCommand));
        private DelegateCommand<object> shiftUpCommand;
        public DelegateCommand<object> ShiftUpCommand =>
            shiftUpCommand ?? (shiftUpCommand = new DelegateCommand<object>(ExecuteShiftUpCommand));
        private DelegateCommand<object> shiftDownCommand;
        public DelegateCommand<object> ShiftDownCommand =>
            shiftDownCommand ?? (shiftDownCommand = new DelegateCommand<object>(ExecuteShiftDownCommand));
        private DelegateCommand<object> list1RowEditEndingCommand;
        public DelegateCommand<object> List1RowEditEndingCommand =>
            list1RowEditEndingCommand ?? (list1RowEditEndingCommand = new DelegateCommand<object>(ExecuteList1RowEditEndingCommand));
        private DelegateCommand updateLotNoCommand;
        public DelegateCommand UpdateLotNoCommand =>
            updateLotNoCommand ?? (updateLotNoCommand = new DelegateCommand(ExecuteUpdateLotNoCommand));

        async void ExecuteUpdateLotNoCommand()
        {
            try
            {
                var str = UPLotNo.Replace(" ", "");
                if (str != string.Empty)
                {
                    if (await CheckLot(str))
                    {
                        using var mdb = new MDbContext();
                        var _param = mdb.MParams.FirstOrDefault(p => p.Name == "PartNum");
                        if (_param != null)
                        {
                            _param.Value = partNum;
                            mdb.SaveChanges();
                        }
                        addMessage($"更新料号\"{partNum}\"");
                        aggregator.SendMessage($"PartNumChanged;{partNum}", "Run");
                        loadLots(partNum, productIndex);
                    }
                }
                else
                {
                    MessageBox.Show("Lot号不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            {
                using var mdb = new MDbContext();
                var param = mdb.MParams.FirstOrDefault(p => p.Name == "UPLotNo");
                if (param != null)
                {
                    param.Value = UPLotNo;
                    mdb.SaveChanges();
                }
            }

        }
        void ExecuteList1RowEditEndingCommand(object obj)
        {
            if (obj is Tony_LOT_NODisp pcs)
            {
                using var mdb = new MDbContext();
                var _lot = mdb.MLotNos.FirstOrDefault(lo => lo.Id == pcs.Id);
                if (_lot != null)
                {
                    _lot.LotNo = pcs.LotNo;
                    _lot.PartNo = pcs.PartNo;
                    mdb.SaveChanges();
                }
            }
        }
        void ExecuteShiftDownCommand(object obj)
        {
            if (obj is Tony_LOT_NODisp pcs)
            {
                bool changed = false;

                using var mdb = new MDbContext();
                var _lot = mdb.MLotNos.FirstOrDefault(lo => lo.Id == pcs.Id);
                int pcsorder = _lot.PcsOrder;
                var _lots = mdb.MLotNos.Where(lo => lo.PcsOrder > pcsorder).OrderBy(lo => lo.PcsOrder);
                if (_lots.Any())
                {
                    var arr = _lots.ToArray();
                    int box = arr[0].PcsOrder;
                    int id = arr[0].Id;
                    int box1 = pcsorder;
                    _lot.PcsOrder = box;
                    var n1 = mdb.MLotNos.FirstOrDefault(lo => lo.Id == id);
                    if (n1 != null)
                    {
                        n1.PcsOrder = pcsorder;
                        mdb.SaveChanges();
                        changed = true;
                    }
                }
                if (changed)
                {
                    loadLots(partNum, productIndex);
                }
            }
        }
        void ExecuteShiftUpCommand(object obj)
        {
            if (obj is Tony_LOT_NODisp pcs)
            {
                bool changed = false;

                using var mdb = new MDbContext();
                var _lot = mdb.MLotNos.FirstOrDefault(lo => lo.Id == pcs.Id);
                int pcsorder = _lot.PcsOrder;
                var _lots = mdb.MLotNos.Where(lo => lo.PcsOrder < pcsorder).OrderByDescending(lo => lo.PcsOrder);
                if (_lots.Any())
                {
                    var arr = _lots.ToArray();
                    int box = arr[0].PcsOrder;
                    int id = arr[0].Id;
                    int box1 = pcsorder;
                    _lot.PcsOrder = box;
                    var n1 = mdb.MLotNos.FirstOrDefault(lo => lo.Id == id);
                    if (n1 != null)
                    {
                        n1.PcsOrder = pcsorder;
                        mdb.SaveChanges();
                        changed = true;
                    }
                }
                if (changed)
                {
                    loadLots(partNum, productIndex);
                }
            }
        }
        void ExecuteDeletCommand(object obj)
        {
            if (obj is Tony_LOT_NODisp pcs)
            {
                if (MessageBox.Show($"确认删除吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    using var mdb = new MDbContext();
                    var _lot = mdb.MLotNos.FirstOrDefault(lo => lo.Id == pcs.Id);
                    if (_lot != null)
                    {
                        mdb.MLotNos.Remove(_lot);
                        mdb.SaveChanges();
                    }
                    loadLots(partNum, productIndex);
                }
            }
        }
        void ExecuteAddCommand()
        {
            DialogParameters param = new DialogParameters();
            _dialogService.ShowDialog("AddPointDialog", param, arg => {
                if (arg.Result == ButtonResult.Yes)
                {
                    //var lotNo = arg.Parameters.GetValue<string>("LotNo");
                    var partNo = arg.Parameters.GetValue<string>("PartNo");
                    if (lotNo != string.Empty && partNo != string.Empty)
                    {
                        using var mdb = new MDbContext();
                        var _lots = mdb.MLotNos.Where(lo => lo.PartNum == partNum && lo.ProductIndex == productIndex);
                        int pcsorder = _lots.Any() ? _lots.Count() : 0;
                        mdb.MLotNos.Add(new MLotNo { 
                            PcsOrder = pcsorder,
                            LotNo = "NA",
                            PartNo = partNo,
                            PartNum = partNum,
                            ProductIndex = productIndex
                        });
                        mdb.SaveChanges();
                        loadLots(partNum, productIndex);
                    }
                    else
                    {
                        MessageBox.Show("料号或Lot号不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            });
        }
        void ExecuteSelectProductLotSettingCommand(object obj)
        {
            if (obj is string str)
            {
                productIndex = int.Parse(str);
                loadLots(partNum, productIndex);
            }
        }
        void ExecuteSelectRuleCheckBoxCommand(object obj)
        {
            if (obj is int id)
            {
                var rule = SelectRuleList.FirstOrDefault(x => x.Id == id);
                using var mdb = new MDbContext();
                var _select = mdb.SelectRules.FirstOrDefault(s => s.Id == id);
                if (_select != null)
                {
                    _select.IsUse = rule.IsUse;
                    mdb.SaveChanges();
                }
            }
        }
        void ExecuteAppLoadedEventCommand()
        {
            using var mdb = new MDbContext();
            var param = mdb.MParams.FirstOrDefault(p => p.Name == "MachineCode");
            if (param != null)
            {
                MachineCode = param.Value;
            }
            else
            {
                MachineCode = "DA-CS-SLJ1-001";
                mdb.MParams.Add(new MParam { Name = "MachineCode", Value = MachineCode, Hand = 0 });
                mdb.SaveChanges();
            }
            param = mdb.MParams.FirstOrDefault(p => p.Name == "ProcessCode");
            if (param != null)
            {
                ProcessCode = param.Value;
            }
            else
            {
                ProcessCode = "NE207";
                mdb.MParams.Add(new MParam { Name = "ProcessCode", Value = ProcessCode, Hand = 0 });
                mdb.SaveChanges();
            }
            param = mdb.MParams.FirstOrDefault(p => p.Name == "UPLotNo");
            if (param != null)
            {
                UPLotNo = param.Value;
            }
            else
            {
                UPLotNo = "111111111";
                mdb.MParams.Add(new MParam { Name = "UPLotNo", Value = UPLotNo, Hand = 0 });
                mdb.SaveChanges();
            }
            SelectRuleList.Clear();
            var _selectRules = mdb.SelectRules.Where(s => s.Id > -1).OrderBy(s => s.ItemNum);
            if (_selectRules.Any())
            {
                _selectRules.ToList().ForEach(s =>
                {
                    SelectRuleList.Add(new SelectRuleDisp
                    {
                        Id = s.Id,
                        Content = $"{s.ItemNum}.{s.Content}",
                        IsUse = s.IsUse
                    });
                });
            }
        }
        void ExecuteTextBoxLostFocusCommand(object obj)
        {
            if (obj is string str)
            {
                switch (str)
                {
                    case "MachineCode":
                        {
                            using var mdb = new MDbContext();
                            var _param = mdb.MParams.FirstOrDefault(p => p.Name == "MachineCode");
                            if (_param != null)
                            {
                                _param.Value = MachineCode;
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "ProcessCode":
                        {
                            using var mdb = new MDbContext();
                            var _param = mdb.MParams.FirstOrDefault(p => p.Name == "ProcessCode");
                            if (_param != null)
                            {
                                _param.Value = ProcessCode;
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "LotNo":
                        {
                            using var mdb = new MDbContext();
                            var _param = mdb.MParams.FirstOrDefault(p => p.Name == "LotNo" && p.PartNum == partNum && p.Hand == productIndex);
                            if (_param != null)
                            {
                                _param.Value = LotNo;
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "ProductNo":
                        {
                            using var mdb = new MDbContext();
                            var _param = mdb.MParams.FirstOrDefault(p => p.Name == "ProductNo" && p.PartNum == partNum && p.Hand == productIndex);
                            if (_param != null)
                            {
                                _param.Value = ProductNo;
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        #endregion
        #region 构造函数
        public ViewAViewModel(IContainerProvider containerProvider)
        {
            SelectRuleList = new ObservableCollection<SelectRuleDisp>();
            Tony_LOT_NOs = new ObservableCollection<Tony_LOT_NODisp>();
            aggregator = containerProvider.Resolve<IEventAggregator>();
            _dialogService = containerProvider.Resolve<IDialogService>();
            //snclient = new RestClient("http://prod-webiis-02.tonytech.com:8012/GetSN_Det.asmx/");
            //fpcclient = new RestClient("http://prod-webiis-02.tonytech.com:8011/FPCSNSelect.asmx/");
            //machineDataclient = new RestClient("http://prod-webiis-02.tonytech.com:8070/MachineData.asmx/");
            snclient = new RestClient("http://prod-webiis-02.tonytech.com:9035/GetSN_Det.asmx/");
            fpcclient = new RestClient("http://prod-webiis-02.tonytech.com:9040/FPCSNSelect.asmx/");
            machineDataclient = new RestClient("http://prod-webiis-02.tonytech.com:9030/MachineData.asmx/");
            aggregator.ResgiterMessage(async arg =>
            {
                var strs = arg.Message.Split(new char[] { ';' });

                switch (strs[0])
                {
                    case "PartNum":
                        {
                            partNum = strs[1];

                            System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                            {
                                loadLots(partNum, productIndex);
                            }));
                           
                        }
                        break;
                    case "CheckBarcode":
                        {
                            bool r = true;
                            if (true || await CheckBarcodesAsync(int.Parse(strs[2]), strs[1]))
                            {
                                //addMessage("条码合规检查完成");
                                if (true || await CheckFPCPass(strs[1]))
                                {
                                    //addMessage("FPC良品检查完成");
                                    if (await UploadBarcode(strs[1]))
                                    {
                                        addMessage("条码上传完成");
                                    }
                                    else
                                    {
                                        r = false;
                                    }
                                }
                                else
                                {
                                    r = false;
                                }
                            }
                            else
                            {
                                r = false;
                            }
                            aggregator.SendMessage($"MESResult;{r}", "MES");
                        }
                        break;
                    default:
                        break;
                }
            }, "MES");
        }
        #endregion
        #region 功能函数
        void loadLots(string partNum,int productIndex)
        {
            using var mdb = new MDbContext();
            var _param = mdb.MParams.FirstOrDefault(p => p.Name == "LotNo" && p.Hand == productIndex && p.PartNum == partNum);
            if (_param != null)
            {
                LotNo = _param.Value;
            }
            else
            {
                LotNo = "9999";
                mdb.MParams.Add(new MParam { 
                    Name = "LotNo",
                    Hand = productIndex, PartNum = partNum,Value = LotNo
                });
                mdb.SaveChanges();
            }
            _param = mdb.MParams.FirstOrDefault(p => p.Name == "ProductNo" && p.Hand == productIndex && p.PartNum == partNum);
            if (_param != null)
            {
                ProductNo = _param.Value;
            }
            else
            {
                ProductNo = "99999999";
                mdb.MParams.Add(new MParam
                {
                    Name = "ProductNo",
                    Hand = productIndex,
                    PartNum = partNum,
                    Value = ProductNo
                });
                mdb.SaveChanges();
            }
            int _index = 1;
            Tony_LOT_NOs.Clear();
            var _lots = mdb.MLotNos.Where(p => p.PartNum == partNum && p.ProductIndex == productIndex).OrderBy(p => p.PcsOrder);
            if (_lots.Any())
            {
                _lots.ToList().ForEach(p => {
                    Tony_LOT_NOs.Add(new Tony_LOT_NODisp { 
                        Id = p.Id,
                        Index1 = _index,
                        LotNo = p.LotNo,
                        PartNo = p.PartNo
                    });
                    _index++;
                });
            }
        }
        async Task<bool> CheckLot(string str)
        {
            List<Parameter1> parm = new List<Parameter1>();
            parm.Add(new Parameter1
            {
                Name = "RCNO",
                Value = str
            });
            try
            {
                var request = new RestRequest("GetRCNO_Part", Method.Post);
                request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
                foreach (var item in parm)
                {
                    request.AddParameter(item.Name, item.Value);
                }
                var response = await snclient.ExecuteAsync(request);
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var res = JsonConvert.DeserializeObject<Tony_GetSN_RCNO>(response.Content);
                    addMessage($"res:{res.res};msg:{res.msg};part_no:{res.part_no}");
                    if (res.res == "OK")
                    {
                        using var mdb = new MDbContext();
                        var _newpart = mdb.PartNums.FirstOrDefault(pa => pa.Name == res.part_no);
                        if (_newpart != null)
                        {
                            if (partNum != res.part_no)
                            {
                                partNum = res.part_no;
                            }
                            else
                            {
                                addMessage($"料号\"{res.part_no}\"就是当前料号");
                                return false;
                            }                    
                        }
                        else
                        {
                            addMessage($"料号\"{res.part_no}\"未建立");
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    addMessage("请求失败");
                    return false;
                }
            }
            catch (Exception ex)
            {
                addMessage(ex.Message);
                return false;
            }
            return true;
        }
        private void addMessage(string str)
        {
            logger.Info(str);
            string[] s = MessageStr.Split('\n');
            if (s.Length > 1000)
            {
                MessageStr = "";
            }
            if (MessageStr != "")
            {
                MessageStr += "\n";
            }
            MessageStr += DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " " + str;
        }
        async Task<bool> CheckBarcodesAsync(int productIndex1,string barcodes)
        {
            var bars = barcodes.Split(new char[] { ',' });
            if (bars.Length == 3)
            {
                //CCS码
                try
                {
                    List<Parameter1> parm = new List<Parameter1>();
                    parm.Add(new Parameter1
                    {
                        Name = "sn",
                        Value = bars[0]
                    });
                    var request = new RestRequest("GetSN_PartLot", Method.Post);
                    request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
                    foreach (var item in parm)
                    {
                        request.AddParameter(item.Name, item.Value);
                    }
                    var response = await snclient.ExecuteAsync(request);

                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        var res = JsonConvert.DeserializeObject<Tony_GetSN_PartLot>(response.Content);
                        addMessage($"res:{res.res};msg:{res.msg};part_no:{res.part_no};lot:{res.lot}");
                        if (res.res == "OK")
                        {
                            using var mdb = new MDbContext();
                            var _ccslot = mdb.MParams.FirstOrDefault(m => m.PartNum == partNum && m.Name == "LotNo" && m.Hand == productIndex1);
                            if (_ccslot != null)
                            {
                                var _ccsproductNo = mdb.MParams.FirstOrDefault(m => m.PartNum == partNum && m.Name == "ProductNo" && m.Hand == productIndex1);
                                if (_ccsproductNo != null)
                                {
                                    if (res.lot != _ccslot.Value || res.part_no != _ccsproductNo.Value)
                                    {
                                        if (res.lot != _ccslot.Value)
                                        {
                                            addMessage("CCS条码Lot号异常");
                                        }
                                        if (res.part_no != _ccsproductNo.Value)
                                        {
                                            addMessage("CCS条码料号异常");
                                        }
                                        return false;
                                    }
                                }
                                else
                                {
                                    addMessage("CCS->料号数据库未配置");
                                    return false;
                                }
                            }
                            else
                            {
                                addMessage("CCS->Lot号数据库未配置");
                                return false;
                            }
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    addMessage(ex.Message);
                    return false;
                }
                //FPC码
                try
                {
                    using var mdb = new MDbContext();
                    var _lots = mdb.MLotNos.Where(m => m.ProductIndex == productIndex1 && m.PartNum == partNum).OrderBy(p => p.PcsOrder);
                    if (_lots != null)
                    {
                        if (_lots.Count() > 1)
                        {
                            var lotarr = _lots.ToArray();
                            for (int i = 0; i < 2; i++)
                            {
                                List<Parameter1> parm = new List<Parameter1>();
                                parm.Add(new Parameter1
                                {
                                    Name = "sn",
                                    Value = bars[i + 1]
                                });
                                var request = new RestRequest("GetSN_PartLot", Method.Post);
                                request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
                                foreach (var item in parm)
                                {
                                    request.AddParameter(item.Name, item.Value);
                                }
                                var response = await snclient.ExecuteAsync(request);

                                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                                {
                                    var res = JsonConvert.DeserializeObject<Tony_GetSN_PartLot>(response.Content);
                                    addMessage($"res:{res.res};msg:{res.msg};part_no:{res.part_no};lot:{res.lot}");
                                    if (res.res == "OK")
                                    {
                                        if (res.part_no != lotarr[i].PartNo)
                                        {
                                            if (res.part_no != lotarr[i].PartNo)
                                            {
                                                addMessage($"FPC条码料号异常:{res.part_no}|{lotarr[i].PartNo}");
                                            }
                                            return false;
                                        }
                                    }
                                    else
                                    {
                                        return false;
                                    }
                                }
                                else
                                {
                                    return false;
                                }
                            }
                        }
                        else
                        {
                            addMessage("FPC->Lot数据库条目少于2条");
                            return false;
                        }
                    }
                    else
                    {
                        addMessage("FPC->Lot数据库未配置");
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    addMessage(ex.Message);
                    return false;
                }
            }
            else
            {
                addMessage($"条码数量异常");
                return false;
            }
            return true;
        }
        async Task<bool> CheckFPCPass(string barcodes)
        {
            bool result = true;
            var bars = barcodes.Split(new char[] { ',' });
            if (bars.Length == 3)
            {
                try
                {
                    for (int i = 0; i < 2; i++)
                    {
                        List<Parameter1> parm = new List<Parameter1>();
                        parm.Add(new Parameter1
                        {
                            Name = "sn",
                            Value = bars[i + 1]
                        });

                        var request = new RestRequest("SelectSN", Method.Post);
                        request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
                        foreach (var item in parm)
                        {
                            request.AddParameter(item.Name, item.Value);
                        }
                        var response = await fpcclient.ExecuteAsync(request);

                        if (response.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            var res = JsonConvert.DeserializeObject<Tony_SelectSN>(response.Content);
                            if (res.msg != "OK")
                            {
                                int ruleNum = int.Parse(res.res);
                                using var mdb = new MDbContext();
                                var _rule = mdb.SelectRules.FirstOrDefault(se => se.ItemNum == ruleNum);
                                if (_rule != null)
                                {
                                    addMessage($"{_rule.ItemNum}.{_rule.Content}");
                                    if (_rule.IsUse)
                                    {
                                        addMessage("FPC良品检查-异常");
                                        result = false;
                                        break;
                                    }
                                    else
                                    {
                                        addMessage("FPC良品检查-放行");
                                    }
                                }
                                else
                                {
                                    addMessage("FPC良品检查-异常");
                                    result = false;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            result = false;
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    addMessage(ex.Message);
                    result = false;
                }
            }
            else
            {
                addMessage("条码数量异常");
                result = false;
            }
            return result;
        }
        async Task<bool> UploadBarcode(string barcodes)
        {
            var bars = barcodes.Split(new char[] { ',' });
            if (bars.Length > 1)
            {
                try
                {
                    List<Parameter1> parm = new List<Parameter1>();
                    parm.Add(new Parameter1
                    {
                        Name = "SN",
                        Value = bars[0]
                    });
                    parm.Add(new Parameter1
                    {
                        Name = "MachineCode",
                        Value = machineCode
                    });
                    parm.Add(new Parameter1
                    {
                        Name = "ProcessCode",
                        Value = processCode
                    });
                    string str = string.Empty;
                    for (int i = 1; i < bars.Length; i++)
                    {
                        str += $"{i}!{bars[i]}|";
                    }
                    parm.Add(new Parameter1
                    {
                        Name = "ParameterAll",
                        Value = str
                    });

                    var request = new RestRequest("MachineData", Method.Post);
                    request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
                    foreach (var item in parm)
                    {
                        request.AddParameter(item.Name, item.Value);
                    }
                    var response = await machineDataclient.ExecuteAsync(request);

                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        addMessage(response.Content);
                        var r = response.Content.Contains("OK");
                        if (!r)
                        {
                            addMessage("条码上传异常");
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    addMessage(ex.Message);
                    return false;
                }
            }
            else
            {
                addMessage("条码数量异常");
                return false;
            }
            return true;
        }
        #endregion
    }
    public class SelectRuleDisp
    {
        public int Id { get; set; }
        public string Content { get; set; }
        public bool IsUse { get; set; }
    }
    public class Tony_LOT_NODisp
    {
        public int Id { get; set; }
        public int Index1 { get; set; }
        public string LotNo { get; set; }
        public string PartNo { get; set; }
    }
    public class Parameter1
    {
        public string Name { get; set; }
        public string Value { get; set; }
    }
    public class Tony_GetSN_RCNO
    {
        public string res { get; set; }
        public string msg { get; set; }
        public string part_no { get; set; }
    }
    public class Tony_GetSN_PartLot
    {
        public string res { get; set; }
        public string msg { get; set; }
        public string part_no { get; set; }
        public string lot { get; set; }
    }
    public class Tony_SelectSN
    {
        public string res { get; set; }
        public string msg { get; set; }
    }
}
